package net.cardgame.orcalecard;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.NoSuchPaddingException;

import jp.jma.oraclecard.MyApplication;
import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.common.ThreadLoadImage;
import net.cardgame.orcalecard.bean.DeckBean;
import net.cardgame.orcalecard.bean.SettingApp;
import net.cardgame.orcalecard.utils.ConstantValue;
import net.cardgame.orcalecard.utils.FileUtils;
import net.cardgame.orcalecard.utils.Utils;
import uk.co.senab.bitmapcache.BitmapLruCache;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class CardDeckActivity extends Activity implements OnClickListener {
	int deckId;
	DeckBean deckBean;
	final static int SWITCH_1_3 = 99;
	SettingApp setting;
	ImageView img_bg_card_deck, img_csdt1_3;
	Intent intent;
	boolean flag = true;
	boolean continueFlow = false;
	int number_of_card = 0;
	final static int requestcodeInfoDeck = 10;
	int cardTotal = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setting = ConstantValue.getSettingApp(this);
		deckBean = new DeckBean();
		Bundle bundle = this.getIntent().getExtras();
		deckId = bundle.getInt("deckId");
		deckBean.deckId = deckId;
		if (bundle.containsKey("deckName"))
			deckBean.deckName = bundle.getString("deckName");
		if (bundle.containsKey("deckPrice"))
			deckBean.deckPrice = bundle.getInt("deckPrice");
		if (bundle.containsKey("deckPathServer"))
			deckBean.pathServerDownload = bundle.getString("deckPathServer");
		if (bundle.containsKey("cardTotal")) {
			cardTotal = bundle.getInt("cardTotal");
		}
		setContentView(R.layout.card_deck_activity);
		img_csdt1_3 = (ImageView) findViewById(R.id.img_csdt1_3);
		img_bg_card_deck = (ImageView) findViewById(R.id.img_bg_card_deck);
		findViewById(R.id.btnhelp_card_deck).setOnClickListener(this);
		findViewById(R.id.btn_back_to_mypage).setOnClickListener(this);
		findViewById(R.id.btn_info_deck).setOnClickListener(this);
		findViewById(R.id.btn_goto_gallery).setOnClickListener(this);
		findViewById(R.id.btn_setting_card_deck).setOnClickListener(this);
		findViewById(R.id.btn_select_one_card).setOnClickListener(this);
		findViewById(R.id.btn_select_three_card).setOnClickListener(this);
		loadImage();
		if (deckId != 999) {
			loadDataImageThread loadBitmap = new loadDataImageThread();
			loadBitmap.start();
		} else {
			continueFlow = true;
		}
	}

	void loadImage() {
		if (deckId == 999) {
			img_bg_card_deck.setImageResource(R.drawable.c999t);
			img_csdt1_3.setImageResource(R.drawable.c999t1_3);
			return;
		}
		new ThreadLoadImage(this, handler1, ConstantValue.getPathDeckImage(
				this, deckId, "t"), img_bg_card_deck, 1).start();
		new ThreadLoadImage(this, handler1, ConstantValue.getPathDeckImage(
				this, deckId, "t1-3"), img_csdt1_3, 2).start();
	}

	Handler handler1 = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:

				img_bg_card_deck.setImageDrawable((Drawable) msg.obj);

				break;
			case 2:
				BitmapDrawable drawabe = (BitmapDrawable) msg.obj;
				if (drawabe != null && !drawabe.getBitmap().isRecycled()) {
					img_csdt1_3.setImageDrawable((Drawable) msg.obj);
					continueFlow = true;
				}
				break;
			case 10:
				gotoSplashActivity();
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (!flag)
			return;
		else
			flag = false;
		switch (v.getId()) {

		case R.id.btnhelp_card_deck:// go to help Activity
			intent = new Intent(this, HelpActivity.class);
			intent.putExtra(HelpActivity.KEY_HELP_INDEX, 4);
			startActivityForResult(intent, 4);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			break;
		case R.id.btn_back_to_mypage:// back to My Page
			if (bitmapBackImage != null) {
				bitmapBackImage.recycle();
			}
			backtoToppageActivity();
			break;

		case R.id.btn_info_deck:// go to deck bean information activity
			passDeck(deckBean);
			break;

		case R.id.btn_goto_gallery:// go to card gallery activity
			intent = new Intent(this, GalleryActivity.class);
			intent.putExtras(getIntent().getExtras());
			startActivity(intent);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			this.finish();
			break;

		case R.id.btn_setting_card_deck: // go to deck bean setting activity
			Intent intent2 = new Intent(this, SettingActiviy.class);
			startActivityForResult(intent2, 0);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			break;
		case R.id.btn_select_three_card: // selected get three card
			number_of_card = setting.adviseCard ? 4 : 3;
			if (deckId == 999) {
				gotoSplashActivity();
			} else
				new ThreadLoadImage(this, handler1,
						ConstantValue.getPathBackgroundByDeckId(this, deckId),
						null, 10).start();

			break;
		case R.id.btn_select_one_card: // selected get one card
			number_of_card = 1;
			if (deckId == 999) {
				gotoSplashActivity();
			} else
				new ThreadLoadImage(this, handler1,
						ConstantValue.getPathBackgroundByDeckId(this, deckId),
						null, 10).start();
			break;
		default:
			break;
		}
	}

	private void gotoSplashActivity() {
		if (continueFlow) {
			intent = new Intent(this, SplashDeckBeanActivity.class);
			intent.putExtras(getIntent().getExtras());
			intent.putExtra("number_of_card", number_of_card);
			startActivity(intent);
			overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
			if (bitmapBackImage != null) {
				bitmapBackImage.recycle();
			}
			this.finish();
		}
	}

	/**
	 * @param dec
	 *            DeckBean pass to InfoDeckActivity
	 */
	public void passDeck(DeckBean dec) {
		Intent intent = new Intent(this, InfoDeckActivity.class);
		intent.putExtras(getIntent().getExtras());
		intent.putExtra("requestCode", requestcodeInfoDeck);
		startActivityForResult(intent, requestcodeInfoDeck);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == requestcodeInfoDeck
				&& resultCode == RESULT_FIRST_USER) {
			this.finish();
		} else {
			setting = ConstantValue.getSettingApp(this);
			flag = true;
			overridePendingTransition(R.anim.slide_in_left,
					R.anim.slide_out_right);
		}
	}

	public static Bitmap bitmapBackImage = null;

	public void loadBitmapToCache() {
		String strDeckId = (deckId < 10) ? ("0" + deckId) : ("" + deckId);
		String path = ConstantValue.getPatchCardData(this) + "Card_"
				+ strDeckId + "/en_c" + strDeckId + "d.png";

		byte[] bytes = null;
		try {
			bytes = FileUtils.decryptToByteArray(path, "");
			bitmapBackImage = BitmapFactory.decodeByteArray(bytes, 0,
					bytes.length);
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (bitmapBackImage != null)
			bitmapBackImage = FileUtils.createReflectedImage(bitmapBackImage);
	}

	Handler handler = new Handler();

	class loadDataImageThread extends Thread {
		public void run() {
			handler.post(new Runnable() {

				@Override
				public void run() {
					loadBitmapToCache();
				}
			});
		}
	}

	private void clearCache() {
		if (deckId != 999) {
			BitmapLruCache cache = MyApplication.getInstance().getBitmapCache();
			cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId,
					"s"));
			cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId,
					"p"));
			cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId,
					"m"));
			cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId,
					"d"));
			cache.removeFromMemory(ConstantValue.getPathBackgroundByDeckId(
					this, deckId));
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		backtoToppageActivity();
	}

	void backtoToppageActivity() {
		clearCache();
		Intent i = new Intent(this, TopPageActivity.class);
		startActivity(i);
		overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
		this.finish();
	}

}
